package cn.tedu.banner.management.service.impl;

import cn.tedu.banner.management.dao.perisit.repository.IBannerRepository;
import cn.tedu.banner.management.pojo.entity.Banner;
import cn.tedu.banner.management.pojo.param.BannerAddNewParam;
import cn.tedu.banner.management.pojo.param.BannerParam;
import cn.tedu.banner.management.pojo.vo.BannerAdminVO;
import cn.tedu.banner.management.pojo.vo.BannerIndexVO;
import cn.tedu.banner.management.service.IBannerService;

import cn.tedu.common.enumerator.ServiceCode;
import cn.tedu.common.ex.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BannerServiceImpl implements IBannerService {
    @Autowired
    private IBannerRepository bannerRepository;

    @Override
    public void avatar(Integer sort, BannerAddNewParam bannerAddNewParam) {
       Banner banner=new Banner();
        BeanUtils.copyProperties(bannerAddNewParam,banner);
        banner.setSort(sort);
        int rows = bannerRepository.avatar(banner);

        if (rows!=1){
            String message = "修改失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }

    //添加轮播图
    @Override
    public void addNew(BannerParam bannerParam) {

        Banner banners = bannerRepository.selectBySort(bannerParam.getSort());
        System.out.println(banners);
        if (banners!=null){
            String message = "排序序号已存在，请重试";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        Banner banner = new Banner();
        bannerParam.setBannerImgUrl("");
        BeanUtils.copyProperties(bannerParam, banner);
        int rows = bannerRepository.insert(banner);
        if (rows != 1) {
            String message = "添加失败！";
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    //删除轮播图
    @Override
    public void delete(Long id) {
        Banner count = bannerRepository.count(id);
        if (count==null){
            String message="该数据不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        bannerRepository.deleteById(id);
    }

    //用户首页轮播图展示
    @Override
    public List<BannerIndexVO> listForIndex() {
        return bannerRepository.selectForIndex();
    }

    //管理员轮播图列表
    @Override
    public List<BannerAdminVO> listForAdmin() {
        return bannerRepository.selectForAdmin();
    }
}
